package j.framework.core;

import j.util.web.filter.GenericSecurityFilter;
import org.apache.log4j.MDC;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 验证管理员是否登录的过滤器
 * @author 刘军海
 *
 */
@WebFilter(
		dispatcherTypes = {
				DispatcherType.REQUEST,
				DispatcherType.FORWARD
		},
		urlPatterns = { "/user/*" },
		initParams = { 
				@WebInitParam(name = "rejectUrl", value = "/login"),
				@WebInitParam(name = "nologinHeader", value = "nologin"),
				@WebInitParam(name = "forwardType", value = "redirect")
		})
public final class CheckUserFilter extends GenericSecurityFilter implements Filter {
	/**
	 * 校验管理员是否登录
	 */
	@Override
	protected boolean isValid(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(null == session){
            //会话已结束
            return false;
        }
		LoginUser user = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY);
		boolean b = false;
		if(null != user){
            MDC.put("user_login_name", user.getLoginName());
            MDC.put("user_name", user.getName());
            MDC.put("user_login_id", user.getUserId());
			b = true;
		}
		return b;
	}
}
